package com.abe.libcore.utils.helper

import android.content.Context
import android.content.Intent
import android.support.v4.app.FragmentActivity

class ActivityResultHelper private constructor(activity: FragmentActivity) {
    private val mContext: Context
    private val mRouterFragment: RouterFragment?

    init {
        mContext = activity
        mRouterFragment = getRouterFragment(activity)
    }

    private fun getRouterFragment(activity: FragmentActivity): RouterFragment? {
        var routerFragment: RouterFragment? = findRouterFragment(activity)
        if (routerFragment == null) {
            routerFragment = RouterFragment.newInstance()
            val fragmentManager = activity.supportFragmentManager
            fragmentManager
                    .beginTransaction()
                    .add(routerFragment, TAG)
                    .commitAllowingStateLoss()
            fragmentManager.executePendingTransactions()
        }
        return routerFragment
    }

    private fun findRouterFragment(activity: FragmentActivity): RouterFragment? {
        return activity.supportFragmentManager.findFragmentByTag(TAG) as RouterFragment?
    }

    fun startActivityForResult(clazz: Class<*>, callback: Callback) {
        val intent = Intent(mContext, clazz)
        startActivityForResult(intent, callback)
    }

    fun startActivityForResult(intent: Intent, callback: Callback) {
        mRouterFragment!!.startActivityForResult(intent, callback)
    }

    interface Callback {
        fun onActivityResult(resultCode: Int, data: Intent)
    }

    companion object {

        private const val TAG = "ActivityLauncher"

        fun init(activity: FragmentActivity): ActivityResultHelper {
            return ActivityResultHelper(activity)
        }
    }
}